package com.example.boardroom.newItems;

import android.content.Context;

import com.blankj.utilcode.util.LogUtils;
import com.example.boardroom.demo.room.AppDatabase;
import com.example.boardroom.demo.room.HardwareControlDao;
import com.example.boardroom.demo.room.HardwareControlTable;
import com.example.boardroom.demo.times.EventTimes;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class RoomUtils {
    HardwareControlDao dao;

    public RoomUtils(Context context) {
        dao = AppDatabase.getInstance(context).hardwareControlDao();
    }

    /**
     * 查询数据库
     */
    public void queryDataBase(int id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<HardwareControlTable> tables = dao.getDevicesById2(id);
                for (HardwareControlTable table : tables) {
                    LogUtils.i("lufei_table", table.openStatus);
                }
                extractValidData(tables);
            }
        }).start();
    }

   private String oldOpenStatus = "2";

    /**
     * 提取有效数据
     */
    private void extractValidData(List<HardwareControlTable> tables) {
        List<HardwareControlTable> list = new ArrayList<>();
        for (HardwareControlTable table : tables) {
            if (!table.openStatus.equals(oldOpenStatus)) {
                list.add(table);
            }
            oldOpenStatus = table.openStatus;
        }
        List<QueryTimeStamp> stampList = new ArrayList<>();
        if (list.size() > 1) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).openStatus.equals("2")) {
                    if (i != 0) {
                        stampList.add(new QueryTimeStamp(list.get(i - 1), list.get(i)));
                    }

                }
                LogUtils.i("lufei_table2", list.get(i).openStatus);
            }
        }

        //最后一个状态处理
        if (list.size() > 0) {
            HardwareControlTable hardwareControlTable = list.get(list.size() - 1);
            if (hardwareControlTable.openStatus.equals("1")) {
                stampList.add(new QueryTimeStamp(hardwareControlTable, hardwareControlTable));
            }
        }

        EventBus.getDefault().postSticky(new EventTimes(stampList, 2));
        for (QueryTimeStamp queryTimeStamp : stampList) {
            LogUtils.i("lufei_table3", queryTimeStamp + "-----" + queryTimeStamp, stampList, stampList.size());
        }

    }
}
